package com.jwsoft.manager.core.dao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.module.base.common.util.CommonSecureUtil;
import com.jwsoft.manager.common.enums.EduStatusTypeEnum;
import com.jwsoft.manager.common.vo.eduDataTaskDetail.DataTaskDetailOptionVO;
import com.jwsoft.manager.core.dao.mapper.EduhStudentStatusMapper;
import com.jwsoft.manager.core.dao.mapper.EdutStudentStatusMapper;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.mapper.EduStudentStatusMapper;
import com.jwsoft.manager.core.dao.service.EduDataTaskDetailService;
import com.jwsoft.manager.core.dao.service.EduStudentStatusService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jwsoft.manager.core.dao.service.TableService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 学生学籍表服务实现类
 *
 * @author wangtao
 * @since 2022-12-28
 */
@Service
@Slf4j
public class EduStudentStatusServiceImpl extends ServiceImpl<EduStudentStatusMapper, EduStudentStatus> implements EduStudentStatusService, TableService {

    @Autowired
    private EduDataTaskDetailService detailService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private EdutStudentStatusMapper tStudentStatusMapper;

    @Autowired
    private EduhStudentStatusMapper hStudentStatusMapper;

    //每次处理的数量为1w条数据
    private static final Integer PAGE_SIZE = 10000;

    @Override
    public Integer dataMigration(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduStudentStatusServiceImpl服务的dataMigration()来进行处理迁移数据");
        Integer count = this.baseMapper.selectCountByYear(optionVO.getYear());
        log.info("edu_student_status迁移" + count + "条数据");
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        for (int i = 0; i < totalPages; i++) {
            List<EduStudentStatus> studentStatuses =
                    this.baseMapper.selectByYear(optionVO.getYear(),PAGE_SIZE);
            if (studentStatuses.size() > 0) {
                List<EduhStudentStatus> hStudentStatusList = studentStatuses.stream().map(eduStudentStatus -> {
                    EduhStudentStatus hStudentStatus = new EduhStudentStatus();
                    BeanUtils.copyProperties(eduStudentStatus, hStudentStatus);
                    hStudentStatus.setTaskDetailId(taskDetail.getTaskDetailId());
                    //数据是否已加密，初始状态未加密
                    hStudentStatus.setEncryptFlag(BoolEnum.FALSE.getType());
                    hStudentStatus.setEncryptStatus(EduStatusTypeEnum.dcl.getType());
                    hStudentStatus.setCleanFlag(BoolEnum.FALSE.getType());
                    return hStudentStatus;
                }).collect(Collectors.toList());
                try {
                    this.performDataMigration(hStudentStatusList, studentStatuses.size(),optionVO);
                } catch (Exception e) {
                    log.error("edu_student_status迁移数据发生异常");
                    throw new RuntimeException("EduStudentStatusServiceImpl:" + e);
                }
            }
        }
        return count;
    }

    private void performDataMigration(List<EduhStudentStatus> hStudentStatusList, Integer count, DataTaskDetailOptionVO optionVO) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    int saveHCount = hStudentStatusMapper.saveBatch(hStudentStatusList);
                    if (saveHCount != count) {
                        throw new RuntimeException("数据迁移到历史表失败");
                    }
                    //2.数据销毁
                    EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
                    if (ObjectUtils.isEmpty(taskDetail)) {
                        throw new AppException("任务数据不存在，请检查数据是否有误");
                    }
                    Integer deleteCount = baseMapper.deleteByTaskHistory(taskDetail.getTaskDetailId());
                    if (!count.equals(deleteCount)) {
                        throw new RuntimeException("数据删除失败");
                    }
                    log.info("edu_student_status数据销毁成功！销毁数量：" + count);
                } catch (Exception e) {
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
    }

    @Override
    public void dataEncryption(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduStudentStatusServiceImpl服务的dataEncryption()来进行处理数据加密");
        Integer count = 0;
        if (taskDetail.getEncryptCount() == 0) {
             count = this.baseMapper.selectEncryptionCountByYear(optionVO.getYear(), optionVO.getTaskDetailId());
             taskDetail.setEncryptCount(count);
        }
        Boolean errorFlag = false;
        Integer errorCount = 0;
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        // 计算循环次数 = 总页数
        for (int i = 0; i < totalPages; i++) {
            List<EduhStudentStatus> hStudentStatuses =
                    this.baseMapper.selectEncryptionByYear(optionVO.getYear(), optionVO.getTaskDetailId(),PAGE_SIZE);
            for (EduhStudentStatus hStudentStatus : hStudentStatuses) {
                try {
                    this.encrypt(hStudentStatus);
                    hStudentStatus.setEncryptTime(new Date());
                    hStudentStatus.setEncryptStatus(EduStatusTypeEnum.success.getType());
                    hStudentStatus.setEncryptRemarks("加密成功");
                    hStudentStatus.setEncryptFlag(BoolEnum.TRUE.getType());
                    hStudentStatusMapper.updateById(hStudentStatus);
                } catch (Exception e) {
                    //解密
                    this.decrypt(hStudentStatus);
                    hStudentStatus.setEncryptTime(new Date());
                    hStudentStatus.setEncryptStatus(EduStatusTypeEnum.error.getType());
                    hStudentStatus.setEncryptFlag(BoolEnum.FALSE.getType());
                    hStudentStatus.setEncryptRemarks("加密失败"+e.getMessage());
                    hStudentStatusMapper.updateById(hStudentStatus);
                    errorFlag = true;
                    errorCount++;
                    throw new AppException(e);
                }
            }
        }
        if (!errorFlag) {
            //无异常，返回任务状态
            taskDetail.setEncryptStatus(EduStatusTypeEnum.success.getType());
            taskDetail.setEncryptRemarks("加密成功");
            taskDetail.setEncryptTime(new Date());
        } else {
            taskDetail.setEncryptStatus(EduStatusTypeEnum.error.getType());
            taskDetail.setEncryptTime(new Date());
            taskDetail.setEncryptRemarks(taskDetail.getHandleTable()
                    +"加密失败,加密出错的数据：" + errorCount);
        }
        detailService.updateById(taskDetail);
    }

    private void encrypt(EduhStudentStatus hStudentStatus) {
        if (StringUtils.isNotBlank(hStudentStatus.getIdcard())){
            hStudentStatus.setIdcard(CommonSecureUtil.sm4Encrypt(hStudentStatus.getIdcard()));
        }
        if (StringUtils.isNotBlank(hStudentStatus.getFullName())){
            hStudentStatus.setFullName(CommonSecureUtil.sm4Encrypt(hStudentStatus.getFullName()));
        }
        if (StringUtils.isNotBlank(hStudentStatus.getFatherIdcard())){
            hStudentStatus.setFatherIdcard(CommonSecureUtil.sm4Encrypt(hStudentStatus.getFatherIdcard()));
        }
        if (StringUtils.isNotBlank(hStudentStatus.getFatherName())){
            hStudentStatus.setFatherName(CommonSecureUtil.sm4Encrypt(hStudentStatus.getFatherName()));
        }
        if (StringUtils.isNotBlank(hStudentStatus.getMotherName())){
            hStudentStatus.setMotherName(CommonSecureUtil.sm4Encrypt(hStudentStatus.getMotherName()));
        }
        if (StringUtils.isNotBlank(hStudentStatus.getMotherIdcard())){
            hStudentStatus.setMotherIdcard(CommonSecureUtil.sm4Encrypt(hStudentStatus.getMotherIdcard()));
        }
    }

    private void decrypt(EduhStudentStatus hStudentStatus) {
        if (StringUtils.isNotBlank(hStudentStatus.getIdcard())){
            hStudentStatus.setIdcard(CommonSecureUtil.sm4Decrypt(hStudentStatus.getIdcard()));
        }
        if (StringUtils.isNotBlank(hStudentStatus.getFullName())){
            hStudentStatus.setFullName(CommonSecureUtil.sm4Decrypt(hStudentStatus.getFullName()));
        }
        if (StringUtils.isNotBlank(hStudentStatus.getFatherIdcard())){
            hStudentStatus.setFatherIdcard(CommonSecureUtil.sm4Decrypt(hStudentStatus.getFatherIdcard()));
        }
        if (StringUtils.isNotBlank(hStudentStatus.getFatherName())){
            hStudentStatus.setFatherName(CommonSecureUtil.sm4Decrypt(hStudentStatus.getFatherName()));
        }
        if (StringUtils.isNotBlank(hStudentStatus.getMotherName())){
            hStudentStatus.setMotherName(CommonSecureUtil.sm4Decrypt(hStudentStatus.getMotherName()));
        }
        if (StringUtils.isNotBlank(hStudentStatus.getMotherIdcard())){
            hStudentStatus.setMotherIdcard(CommonSecureUtil.sm4Decrypt(hStudentStatus.getMotherIdcard()));
        }
    }

    @Override
    public Integer dataDestruction(DataTaskDetailOptionVO optionVO) {
        System.out.println("数据销毁");
        return null;
    }

    @Override
    public void tempDataDestruction() {
        System.out.println("空闲数据销毁");
    }

    @Override
    public void dataDecrypt(DataTaskDetailOptionVO optionVO) {
        Integer count = Math.toIntExact(hStudentStatusMapper.selectCount(new QueryWrapper<EduhStudentStatus>().lambda().eq(EduhStudentStatus::getTaskDetailId, optionVO.getTaskDetailId())));
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        int currentPage = 0;
        // 计算循环次数 = 总页数
        for (int i = 0; i < totalPages; i++) {
            List<EduhStudentStatus> hStudentStatuses
                    = hStudentStatusMapper.selectByTaskDetailId(optionVO.getTaskDetailId(),currentPage,PAGE_SIZE);
            List<EdutStudentStatus> tStudentStatusList = hStudentStatuses.stream().map(eduhStudentStatus -> {
                if (BoolEnum.TRUE.getType().equalsIgnoreCase(eduhStudentStatus.getEncryptFlag())) {
                    //需要进行解密
                    this.decrypt(eduhStudentStatus);
                }
                EdutStudentStatus tStudentStatus = new EdutStudentStatus();
                BeanUtils.copyProperties(eduhStudentStatus, tStudentStatus);
                return tStudentStatus;
            }).collect(Collectors.toList());
            tStudentStatusMapper.saveBatch(tStudentStatusList);
            currentPage ++;
        }
    }
}
